export function createProxy(data:object):any {
    let keyList = {}; // 被监听的数据列表
    function isObject(obj) {
        return obj != null && typeof obj === 'object'
    }    
    let toProxyMap = new WeakMap()
    let toRawMap = new WeakMap()
    function createReactiveObject(target) {
        if (!isObject(target)) return target
        if(toProxyMap.has(target)) return toProxyMap.get(target)
        if(toRawMap.has(target)) return target
        const handler:ProxyHandler<object> = {
            get(target, key, receiver) {
                console.log('get', key)
                let res = Reflect.get(target, key, receiver)
                return isObject(res) ? createReactiveObject(res) : res
            },
            set(target, key, value, receiver):boolean {
                // console.log('set', key, value)
                let oldValue = target[key]
                let res = Reflect.set(target, key, value, receiver)
                let hadKey = target.hasOwnProperty(key)
                if(key==='length') {
                    if (keyList.hasOwnProperty(key)) {
                        keyList[key](target)
                    }
                }else if (!hadKey) {
                    if (keyList.hasOwnProperty(key)) {
                        keyList[key](value)
                    }
                } else if (oldValue !== value) {
                    if (keyList.hasOwnProperty(key)) {
                        keyList[key](value)
                    }
                }
                return res
            },
            deleteProperty(target, key):boolean {
                return Reflect.deleteProperty(target, key)
            }
        }
        let objProxy = new Proxy(target, handler)
        toProxyMap.set(target, objProxy)
        toRawMap.set(objProxy, target)
        return objProxy
    }
    let objProxy = createReactiveObject(data);
    objProxy.watch = function (key, callback) {
        keyList[key] = callback;
    }
    // operater.setData(data)
    return objProxy;
}